package cii_lib_graph;


import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import javax.swing.tree.DefaultMutableTreeNode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import plugins.ICIIGraphicable;
import resources.AdvancedView;
import resources.UltimateOPS;
import resources.XmlInterfaceData;
import cii_lib.CCII_ACCESS_INTERF;
import cii_lib.CCII_COMPONENT;
import cii_lib.CII_Tree_Vectors;
import cii_lib_graph.elements.DataCardPane;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class GCII_DPM_DAQ extends javax.swing.JFrame implements ICIIGraphicable{
	
	private static final Logger log = LoggerFactory
			.getLogger(GCII_DPM_DAQ.class);
	private JPanel dispPane;
	private JTree jTree1;
	private JPanel jPanel1;

	private CCII_COMPONENT daq;
	private boolean loaded = false, confpainted=false;
	private JButton clearBut;
	private JLabel jLabel1;
	private JScrollPane jPanel2;
	private JButton defData;
	private JButton dispArray;
	
	private DefaultMutableTreeNode rootComp = new DefaultMutableTreeNode("not loaded");
	
	private Map<CII_Tree_Vectors,XmlInterfaceData> ifDatas 
	=new HashMap<CII_Tree_Vectors,XmlInterfaceData>();

	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			log.error("", e);
		} catch (InstantiationException e) { 
			log.error("", e);
		} catch (IllegalAccessException e) {
			log.error("", e);
		} catch (UnsupportedLookAndFeelException e) {
			log.error("", e);
		}
		GCII_DPM_DAQ inst = new GCII_DPM_DAQ();
		inst.setVisible(true);
	}
	
	/**
	 * @deprecated Use GCII_DPM_DAQ(CCII_COMPONENT comp)
	 */
	public GCII_DPM_DAQ() {
		super();
		initGUI();
	}
	
	public GCII_DPM_DAQ(CCII_COMPONENT comp) {
		super();
		daq=comp;
		loaded = true;
		initGUI();
	}
	
	private void initGUI() {
		try {
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			{
	dispPane = new JPanel();
				getContentPane().add(dispPane, BorderLayout.CENTER);
				dispPane.setLayout(null);
				{
					jPanel1 = new JPanel();
					BorderLayout jPanel1Layout = new BorderLayout();
					jPanel1.setLayout(jPanel1Layout);
					dispPane.add(jPanel1);
					jPanel1.setBounds(161, 14, 609, 385);
					jPanel1.setBorder(BorderFactory.createEtchedBorder(new java.awt.Color(213,240,253), new java.awt.Color(128,0,255)));
				}
				{
					dispArray = new JButton();
					dispPane.add(dispArray);
					dispArray.setText("Display Memory");
					dispArray.setBounds(28, 213, 112, 28);
					dispArray.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) { log.info("Command: {}", evt.getActionCommand());
							clearDisplay();
							addAdvancedView();
							jPanel1.repaint();
							dispArray.setEnabled(false);
							
							dispPane.repaint();
						}
					});
				}
				{
					defData = new JButton();
					dispPane.add(defData);
					defData.setText("Data Card");
					defData.setBounds(28, 247, 112, 28);
					defData.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) { log.info("Command: {}", evt.getActionCommand());
							clearDisplay();
							displayDMI();
							defData.setEnabled(false);
						}
					});
				}
				{
					clearBut = new JButton();
					dispPane.add(clearBut);
					clearBut.setText("Clear");
					clearBut.setBounds(28, 357, 112, 28);
					clearBut.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) { log.info("Command: {}", evt.getActionCommand());
							clearDisplay();
						}
					});
				}
				{
					jPanel2 = new JScrollPane();
//					BorderLayout jPanel2Layout = new BorderLayout();
					dispPane.add(jPanel2);
//					jPanel2.setLayout(jPanel2Layout);
					jPanel2.setBounds(12, 33, 137, 174);
					{
						jTree1 = new JTree(buildTreeModel(daq));
						jTree1.setToolTipText("Right click to config");
						jPanel2.setViewportView(jTree1);
					    jTree1.setCellRenderer(UltimateOPS.treeRenderer());
					    jTree1.setSelectionRow(0);
//					    jTree1.setPreferredSize(new java.awt.Dimension(96, 166));
					    jTree1.addMouseListener(new MouseAdapter() {
					    	public void mouseClicked(MouseEvent evt) {
					    		if (evt.getButton()==3) {
					    			String clicked= (String)jTree1.getSelectionPath().getLastPathComponent().toString();
					    			if (clicked.contains("COMP_DAQ")) configureDAQ();
					    			if (clicked.contains("COMP_FIFO")) configureFIFO();
					    			if (clicked.contains("COMP_DPM")) configureDPM();
					    		}
					    	}
					    });
					    
					}
				}
				{
					jLabel1 = new JLabel();
					dispPane.add(jLabel1);
					jLabel1.setText("Configuration:");
					jLabel1.setBounds(49, 12, 69, 15);
					jLabel1.setForeground(new java.awt.Color(0,0,255));
				}
			}
			pack();
			this.setSize(785, 438);
		} catch (Exception e) {
			log.error("", e);
		}
		dispPane.setSize(785,413);
		dispPane.setPreferredSize(new java.awt.Dimension(777, 413));
	}

	private void clearDisplay() {
		if (jPanel1.getComponents().length>0) jPanel1.remove(0);
		jPanel1.repaint();
		dispArray.setEnabled(true);
		defData.setEnabled(true);
		confpainted=false;
	}
	private void configureDAQ() {
		if (loaded && !confpainted) {
			confpainted=true;
			clearDisplay();
			GComponentManager man = new GComponentManager(daq);
			jPanel1.add(man.getDefaultPanel());
			jPanel1.revalidate();
			return;
		}
		log.debug("Unable to comply : component not loaded");
//		jPanel1.add(comp);
	}
	private void configureFIFO() {
		if (loaded && !confpainted) {
			confpainted=true;
			clearDisplay();
			GComponentManager man = new GComponentManager(daq.getChildren().get(0));
			jPanel1.add(man.getDefaultPanel());
			jPanel1.revalidate();
			return;
		}
		log.debug("Unable to comply : component not loaded");
//		jPanel1.add(comp);
	}
	private void configureDPM() {
		if (loaded && !confpainted) {
			confpainted=true;
			clearDisplay();
			GComponentManager man = new GComponentManager(daq.getChildren().get(0).getChildren().get(0));
			jPanel1.add(man.getDefaultPanel());
			jPanel1.revalidate();
			return;
		}
		log.debug("Unable to comply : component not loaded");
//		jPanel1.add(comp);
	}
	
	public void loadComponent(CCII_COMPONENT comp) {
		daq=comp;
		loaded = true;
	}
	
	/* (non-Javadoc)
	 * @see plugins.ICIIGraphicable#getCustomPane(java.lang.String)
	 */
	public JPanel getCustomPane(String xmlconfig) {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see plugins.ICIIGraphicable#getDefaultPane()
	 */
	public JPanel getDefaultPane() {
		// TODO Auto-generated method stub
		return dispPane;
	}

	/* (non-Javadoc)
	 * @see plugins.ICIIGraphicable#getGCIIName()
	 */
	public String getGCIIName() {
		// TODO Auto-generated method stub
		return "GCII_DPM_DAQ";
	}
	
	private void displayDMI() {
		if (!loaded) return;
		DataCardPane dp = new DataCardPane(daq.getChildren().get(0).getChildren().get(0).getInterfaces().get(3));
		jPanel1.add(dp.getDefaultPanel());
		confpainted=false;
		jPanel1.revalidate();
	}
	
	private void addAdvancedView()
	{
		if (!loaded) return;
		confpainted=false;
		final AdvancedView tmp=new AdvancedView();
		CCII_ACCESS_INTERF akces = daq.getChildren().get(0).getChildren().get(0).getInterfaces().get(3);
		CII_Tree_Vectors lastInterface = new CII_Tree_Vectors(akces.GetItem());
//		lastInterface = daq.getChildren().get(0).getChildren().get(0).getInterfaces().get(3);
//		vAdvViews.add(tmp);
		XmlInterfaceData xdata = new XmlInterfaceData();
		xdata.setInterface(lastInterface);
		AdvancedView.AdvancedInterfaceTablePanel tbl=tmp.addInterface(lastInterface,xdata);
		tbl.setInterfaceAccess(akces);
		jPanel1.add(tmp.getMainPanel());
		jPanel1.revalidate();
//		tmp.getScrollPanel().setViewportView(jPanel1);
//		tmp.setVisible(true);
		
//		tmp.addWindowListener( new WindowAdapter() 
//		{ 
//			public void windowClosing(WindowEvent e)
//			{ 
//				Iterator<CII_Tree_Vectors> it=tmp.getInterfaces().iterator();
//				while(it.hasNext())
//				{
//					CII_Tree_Vectors face=it.next();
//					AdvancedView.AdvancedInterfaceTablePanel pnl=tmp.getInterfaceTable(face);
//					String fname="./Cache/"+face.getLink()+"/"+face.Clear(1)+"/data.xml";
//					try {
//						File file=new File(fname);
//						if(!file.exists())
//						{
//							try {
//								file.getParentFile().mkdirs();
//								file.createNewFile();
//							} catch (IOException e3) {
//								e3.printStackTrace();
//							}
//						}
//						pnl.getInterfaceData().exportXML(new FileOutputStream(file),null);
//					} catch (FileNotFoundException e1) {
//						e1.printStackTrace();
//					}			
//				}
//				tmp.dispose();
//			} 
//		});
//		tbl.setAccessMode(selectedAccessMode);
	}
	
	public DefaultMutableTreeNode buildTreeModel(CCII_COMPONENT comp) {
		if (loaded) {
		    return UltimateOPS.buildTreeModel(comp);
		}
		return null;
	}
	
}
